package megrez.common.util;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import lombok.experimental.UtilityClass;

/**
 * Java工具
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class JavaHelper {
    public Path getJavaCmd() throws IOException {
        String javaHome = System.getProperty("java.home");
        Path javaCmd;
        if (OsHelper.isWin()) {
            javaCmd = Paths.get(javaHome, "bin", "java.exe");
        } else {
            javaCmd = Paths.get(javaHome, "bin", "java");
        }
        if (javaCmd.toFile().canExecute()) {
            return javaCmd;
        } else {
            throw new UnsupportedOperationException(javaCmd.toString() + " is not executable");
        }
    }
    
    public  Process runClass(Class<?> clazz) throws IOException, InterruptedException {
        String classpath = System.getProperty("java.class.path");
        String javaBin = getJavaCmd().toString();
        
        ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, clazz.getCanonicalName());
        builder.inheritIO();
        return builder.start();
    }  
}
